package top.rish.converter.solon;

import org.noear.solon.Solon;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.Plugin;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.core.util.LogUtil;
import top.rish.converter.core.factory.SolonDictConvertFactory;
import top.rish.converter.core.annotation.handler.DictConvertHandler;

import java.util.Objects;

public class DictionaryConverterImpl implements Plugin, RouterInterceptor {

    @Override
    public void start(AppContext context) throws Throwable {
        //订阅 ConvertHandler （订阅方式，可时实获取；也方便任何时候接收新构建）
        context.subBeansOfType(DictConvertHandler.class, SolonDictConvertFactory::registerHandler);

        //装配 Config（单个类的话，beanMake 比 beanSacn 性能好）
        context.beanMake(DictionaryConfiguration.class);

        //注册 RouterInterceptor（路由拦截器，比注解拦截器更适合）
        Solon.app().routerInterceptor(this);
    }

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        chain.doIntercept(ctx, mainHandler);
    }

    /**
     * 执行结果确认（是实体转换的最佳时机）
     */
    @Override
    public Object postResult(Context ctx, Object result) throws Throwable {
        long st = System.currentTimeMillis();
        SolonDictConvertFactory.registerDictEntityFields(result);
        Object converted = SolonDictConvertFactory.convert(result);

        if (!Objects.equals(result, converted)) {
            long et = System.currentTimeMillis();
            result = converted;
            LogUtil.global().info("Dictionary Converter use time : " + (et - st)+"ms");
        }

        return result;
    }
}